import { message } from 'antd';
import { websiteService } from '@/services/websiteService';

export interface ImageSize {
  width: number;
  height: number;
}

export interface ImageUploadOptions {
  maxSize?: number; // 最大文件大小 (MB)
  allowedTypes?: string[]; // 允许的文件类型
  autoResize?: boolean; // 是否自动调整大小
  quality?: number; // 图片质量 (0-1)
}

/**
 * 图片上传管理器
 */
export class ImageUploadManager {
  private options: Required<ImageUploadOptions>;

  constructor(options: ImageUploadOptions = {}) {
    this.options = {
      maxSize: 10, // 默认10MB
      allowedTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
      autoResize: false,
      quality: 0.8,
      ...options
    };
  }

  /**
   * 上传图片文件
   */
  async uploadImage(file: File): Promise<string> {
    try {
      // 验证文件
      this.validateFile(file);
      
      // 处理图片
      const processedFile = await this.processImage(file);
      
      // 上传到服务器
      const url = await websiteService.uploadImage(processedFile);
      
      message.success('图片上传成功');
      return url;
    } catch (error) {
      console.error('图片上传失败:', error);
      message.error('图片上传失败');
      throw error;
    }
  }

  /**
   * 验证文件
   */
  private validateFile(file: File): void {
    // 检查文件类型
    if (!this.options.allowedTypes.includes(file.type)) {
      throw new Error(`不支持的文件类型: ${file.type}`);
    }

    // 检查文件大小
    const maxSizeBytes = this.options.maxSize * 1024 * 1024;
    if (file.size > maxSizeBytes) {
      throw new Error(`文件大小超过限制: ${this.options.maxSize}MB`);
    }
  }

  /**
   * 处理图片（压缩、调整大小等）
   */
  private async processImage(file: File): Promise<File> {
    if (!this.options.autoResize) {
      return file;
    }

    return new Promise((resolve, reject) => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      const img = new Image();

      img.onload = () => {
        try {
          // 计算新的尺寸
          const { width, height } = this.calculateDimensions(img.width, img.height);
          
          canvas.width = width;
          canvas.height = height;
          
          // 绘制图片
          ctx?.drawImage(img, 0, 0, width, height);
          
          // 转换为Blob
          canvas.toBlob(
            (blob) => {
              if (blob) {
                const processedFile = new File([blob], file.name, {
                  type: file.type,
                  lastModified: Date.now()
                });
                resolve(processedFile);
              } else {
                reject(new Error('图片处理失败'));
              }
            },
            file.type,
            this.options.quality
          );
        } catch (error) {
          reject(error);
        }
      };

      img.onerror = () => {
        reject(new Error('图片加载失败'));
      };

      img.src = URL.createObjectURL(file);
    });
  }

  /**
   * 计算图片尺寸
   */
  private calculateDimensions(width: number, height: number): { width: number; height: number } {
    const maxWidth = 1920;
    const maxHeight = 1080;

    if (width <= maxWidth && height <= maxHeight) {
      return { width, height };
    }

    const ratio = Math.min(maxWidth / width, maxHeight / height);
    return {
      width: Math.round(width * ratio),
      height: Math.round(height * ratio)
    };
  }

  /**
   * 生成图片HTML标签
   */
  generateImageHTML(url: string, alt: string, size: ImageSize): string {
    return `<img src="${url}" alt="${alt}" width="${size.width}" height="${size.height}" />`;
  }

  /**
   * 生成Markdown格式的图片链接
   */
  generateImageMarkdown(url: string, alt: string): string {
    return `![${alt}](${url})`;
  }

  /**
   * 从URL中提取文件名
   */
  extractFilename(url: string): string {
    const filename = url.split('/').pop() || '图片';
    return filename.split('?')[0]; // 移除查询参数
  }
}

/**
 * 图片选择器组件接口
 */
export interface ImageSelectorProps {
  visible: boolean;
  onClose: () => void;
  onSelect: (url: string) => void;
  imageSize: ImageSize;
  onSizeChange: (type: 'width' | 'height', value: number | null) => void;
}

/**
 * 创建文件选择器
 */
export const createFileSelector = (options: ImageUploadOptions = {}): HTMLInputElement => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = options.allowedTypes?.join(',') || 'image/*';
  input.multiple = false;
  
  return input;
};

/**
 * 便捷的图片上传函数
 */
export const uploadImage = async (file: File, options?: ImageUploadOptions): Promise<string> => {
  const manager = new ImageUploadManager(options);
  return manager.uploadImage(file);
};

/**
 * 默认图片上传管理器实例
 */
export const defaultImageUploadManager = new ImageUploadManager();
